﻿var ConfigurationModule = new function () {
    
    var getConfig = function (config) {
        var configuration = Object.assign(config);

        if (configuration.bounds) {
            configuration.bounds = getBounds(configuration.bounds);
            if (configuration.center) delete configuration.center;
        }

        if (!configuration.bounds && configuration.center) {
            configuration.center = getLocation(configuration.center);
        }

        if (configuration.centerOffset) {
            if (!configuration.bounds && configuration.center) {
                configuration.centerOffset = getCenterOffset(configuration.centerOffset);
            }
        }

        if (configuration.labelOverlay) {
            configuration.labelOverlay = Microsoft.Maps.LabelOverlay[configuration.labelOverlay];
        }

        if (configuration.mapTypeId) {
            configuration.mapTypeId = Microsoft.Maps.MapTypeId[configuration.mapTypeId];
        }

        return configuration;
    };

    var getBounds = function(obj){
        var center = getLocation(obj.center);
        var locationRect = new Microsoft.Maps.LocationRect(center, obj.height, obj.width);
        return locationRect;
    };

    var getCenterOffset = function (offset) {
        var point = new Microsoft.Maps.Point(offset.point.x, offset.point.y);
        return point;
    };

    var getLocation = function (center) {
        var location = new Microsoft.Maps.Location(
            center.latitude, center.longitude
        );
        return location;
    };


    this.getConfig = function (config) {
        
        if (!config) {
            console.log("Missing config.");
            return;
        }

        if (config.constructor === String) config = JSON.parse(config);

        var configuration = getConfig(config);

        return configuration;
    }
};

//A Polyfill for Object.assign

if (typeof Object.assign != 'function') {
    (function () {
        Object.assign = function (target) {
            'use strict';
            if (target === undefined || target === null) {
                throw new TypeError('Cannot convert undefined or null to object');
            }

            var output = Object(target);
            for (var index = 1; index < arguments.length; index++) {
                var source = arguments[index];
                if (source !== undefined && source !== null) {
                    for (var nextKey in source) {
                        if (source.hasOwnProperty(nextKey)) {
                            output[nextKey] = source[nextKey];
                        }
                    }
                }
            }
            return output;
        };
    })();
}


Microsoft.Maps.moduleLoaded('ConfigurationModule');